package cn.wgx.safetyhelmet.service.imp;

import cn.wgx.safetyhelmet.entity.User;
import cn.wgx.safetyhelmet.repository.UserRepository;
import cn.wgx.safetyhelmet.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;


@Service
public class UserServiceJpaImp implements UserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public List getUsers(User user) {
        if(user == null){
            return userRepository.findAll();
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//字符串模糊查找
                .withIgnoreCase();//忽略大小写
        Example<User> userExample = Example.of(user,exampleMatcher);
        return userRepository.findAll(userExample,sort);
    }

    @Override
    public User add(User user) {
        user.setId(0l);
        return userRepository.save(user);
    }

    @Override
    public int del(Long id) {
        userRepository.deleteById((long)id);
        return 1;
    }

    @Override
    public int del(String name) {
        User user = new User();
        user.setName( name);
        userRepository.delete(user);
        return 1;
    }

    @Override
    public int update(User user) {
        return userRepository.save(user) == null? 0: 1;
    }

    @Override
    public int getAllUsers() {
        return (int)userRepository.count()-0;
    }

    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id).get();
    }
}
